package com.hl.controller;

import com.hl.entity.User;
import com.hl.requestBody.RequestUser;
import com.hl.response.Response;
import com.hl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    // 查询数据库中的记录，返回给postman
    @GetMapping("/get/{id}")
    public User getUserById(@PathVariable int id) {
        return userService.selectById(id);
    }
    
    @GetMapping("/get_info")
    public Response<User> getUserInfos(@RequestParam(value = "name", required = false) String name,
                                       @RequestParam(value = "age", defaultValue = "0", required = false) int age) {
        Response<User> result = new Response<>(200);
        result.setList(userService.getUserInfos(name, age));
        return result;
    }
    
    @GetMapping("/get_info_exam")
    public Response<User> getUserInfosExam(@Validated RequestUser requestUser) {
        Response<User> result = new Response<>(200);
        result.setList(userService.getUserInfosExam(requestUser));
        return result;
    }
    
    // 保存用户记录（postman发送json字符串）到数据库
    @PostMapping("/save")
    public void postUser(@RequestBody User user) {
        System.out.printf(user.toString());
        userService.saveUser(user);
    }
    
}
